import { computed } from 'vue';
import { RouteRecordRaw, RouteRecordNormalized } from 'vue-router';
import { useAppStore } from '@/store';

export default function useMenuTree() {
  const appStore = useAppStore();
  const appRoute = computed(() => appStore.appAsyncMenus);
  const menuTree = computed(() => {
    const copyRouter = JSON.parse(JSON.stringify(appRoute.value));
    copyRouter.sort((a: RouteRecordNormalized, b: RouteRecordNormalized) => {
      return (a.meta.order || 0) - (b.meta.order || 0);
    });
    function travel(_routes: RouteRecordRaw[], layer: number) {
      if (!_routes) return null;

      const collector: any = _routes.map((element) => {

        if(element.meta?.hidden) {
          return null;
        }

        // route filter hidden true
        if(element.children) {
          element.children = element.children.filter(
            (x) => x.meta?.hidden !== true
          );
          // Associated child node
          const subItem = travel(element.children, layer + 1);

          if (subItem?.length) {
            element.children = subItem;
            return element;
          }
          // the else logic
          if (layer > 1) {
            element.children = subItem;
            return element;
          }
        }
        return element;
      });
      return collector.filter(Boolean);
    }
    return travel(copyRouter, 0);
  });

  return {
    menuTree,
  };
}
